"""依赖注入模块"""

from typing import Generator, Optional

from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials

from app.core.config import settings
from app.utils.logger import get_logger
from app.utils.validators import TextValidator

logger = get_logger("dependencies")

# HTTP Bearer 认证
security = HTTPBearer()


def get_current_user(credentials: HTTPAuthorizationCredentials = Depends(security)) -> str:
    """获取当前用户（简单的API密钥认证）"""
    token = credentials.credentials
    
    # 这里应该实现真实的用户认证逻辑
    # 目前仅作为示例，实际应该验证JWT或API密钥
    if not token:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="缺少认证信息",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    # 简单验证（生产环境应该使用更安全的方式）
    if token != "demo-api-key":
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="无效的认证信息",
            headers={"WWW-Authenticate": "Bearer"},
        )
    
    return "demo-user"


def get_text_validator() -> TextValidator:
    """获取文本验证器实例"""
    return TextValidator(min_length=1, max_length=50000)


def get_logger_instance(name: str = "app"):
    """获取日志实例"""
    return get_logger(name)


class DatabaseDependency:
    """数据库依赖类（示例）"""
    
    def __init__(self):
        self.connection = None
    
    def get_connection(self):
        """获取数据库连接"""
        # 这里应该实现真实的数据库连接逻辑
        if not self.connection:
            # 模拟数据库连接
            logger.info("创建数据库连接")
            self.connection = "mock_db_connection"
        return self.connection
    
    def close_connection(self):
        """关闭数据库连接"""
        if self.connection:
            logger.info("关闭数据库连接")
            self.connection = None


# 全局数据库依赖实例
db_dependency = DatabaseDependency()


def get_database() -> str:
    """获取数据库连接依赖"""
    try:
        connection = db_dependency.get_connection()
        yield connection
    finally:
        # 这里可以添加清理逻辑，但不一定要关闭连接
        pass


class RedisDependency:
    """Redis依赖类"""
    
    def __init__(self):
        self.client = None
    
    def get_client(self):
        """获取Redis客户端"""
        if not self.client:
            # 这里应该实现真实的Redis连接逻辑
            logger.info("创建Redis连接")
            self.client = "mock_redis_client"
        return self.client
    
    def close_client(self):
        """关闭Redis客户端"""
        if self.client:
            logger.info("关闭Redis连接")
            self.client = None


# 全局Redis依赖实例
redis_dependency = RedisDependency()


def get_redis() -> str:
    """获取Redis客户端依赖"""
    try:
        client = redis_dependency.get_client()
        yield client
    finally:
        # Redis连接通常保持长连接，这里不关闭
        pass


def verify_api_key(api_key: Optional[str] = None) -> bool:
    """验证API密钥"""
    if not api_key:
        return False
    
    # 这里应该实现真实的API密钥验证逻辑
    # 可以从数据库或配置中验证
    valid_keys = ["demo-api-key", "test-api-key"]
    return api_key in valid_keys


def get_pagination_params(page: int = 1, size: int = 10) -> dict:
    """获取分页参数"""
    if page < 1:
        page = 1
    if size < 1 or size > 100:
        size = 10
    
    return {
        "page": page,
        "size": size,
        "skip": (page - 1) * size,
        "limit": size
    } 